/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reginAPI;

import exceptions.AuthException;
import exceptions.TokenAuthException;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author bertram
 */
public class Auth {

    private String token;
    public Auth()
    {
        
    }

    private void checkToken(String token) throws TokenAuthException {
       
        if (refresh(token)); else {
            throw new TokenAuthException("invalid token");
        }
    }

    public String login(String username, String password) throws AuthException {
        String res = getToken(username, password);
        if (res.equals("") || res == null || res.equals("__WS_REGIN_NULL__")) {
            throw new AuthException("wrong username or password");
        } else {
            return res;
        }
    }

    public synchronized void checkAuth(HttpServletRequest req) throws AuthException {
        /*ok, hvad gør vi her? vi tager imod et request
        og checker først efter et token, hvis dette ikke findes
        eller checktoken ikke returnerer true kaster vi en authexception
        denne authexception griber vi og finder et username/password i requestet.
        hvis dette ikke returnerer et token, som checktoken accepterer eskalerer vi authexception
        og lader kalderen håndtere den.*/
        token = (String) req.getSession().getAttribute("token");
        boolean loggedIn = false;
        //if(req.getRemoteAddr().equalsIgnoreCase("127.0.0.1"))return;

        if (token == null) {
            
            String username = (String) req.getParameter("username");
            String password = (String) req.getParameter("password");
            if (username == null || password == null) {
                throw new AuthException("no credentials supplied");
            } else {
                token = login(username, password);
            }
       }
        try{
            checkToken(token);
            req.getSession().setAttribute("token", token);
        }
        catch(TokenAuthException tae)
        {
            throw new AuthException("invalid token");
        }


    }

    private static String getToken(java.lang.String username, java.lang.String password) {
        regin.login.LoginService service = new regin.login.LoginService();
        regin.login.LoginServicePortType port = service.getLoginServiceSOAP12PortHttp();
        return port.login(username, password);
    }

    private static Boolean refresh(java.lang.String loginToken) {
        regin.login.LoginService service = new regin.login.LoginService();
        regin.login.LoginServicePortType port = service.getLoginServiceSOAP12PortHttp();
        return port.refresh(loginToken);
    }


}
